package com.ankiang.treeprint.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ankiang.treeprint.R;
import com.ankiang.treeprint.model.LOG;
import com.ankiang.treeprint.model.TRItemNode;
import com.ankiang.treeprint.model.TRItemTree;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;

import java.util.HashMap;
import java.util.Iterator;

import static com.qmuiteam.qmui.util.QMUIDisplayHelper.dp2px;


public class TRLayout extends FrameLayout
        implements ScaleGestureDetector.OnScaleGestureListener/*, View.OnTouchListener*/ {

    private static final String TAG = "TreeGridLayout";

//    private boolean mInvalidateLayout = true;

    // 长按功能
    OnLongClickListener mLongClickListener;

    // 模型数据
    private TRItemTree mItemTree;
    private HashMap<Integer, TextView> mTextViewMap;

    // 配置
    private TRConfig conf;

    private Context mContext;

    // 画线
    private Paint mPaint;
    private Path mPath;

    // 双击放大缩小
    private long mClickTime = 0;
    private int scaleState = ScaleSate.FULL_WIDTH;

    // 放大缩小的百分比
    int percent = 100;

    // 放大缩小
    final static int TREE_NODE_TIPS_GAP_HORIZONTAL = 160;
    final static int TREE_NODE_TIPS_GAP_VERTICAL = 120;
    int treeNodeTipsGapHorizontal = 160; // 水平树空白
    int treeNodeTipsGapVertical = 120; // 垂直树空白


    final static int TREE_NODE_WIDTH = 124;
    final static int TREE_NODE_HEIGHT = 124;
    int treeNodeWidth = 124; // 节点的大小
    int treeNodeHeight = 124; // 节点的大小


    final static int TREE_NODE_TOP_MARGIN = 64;
    final static int TREE_NODE_LEFT_MARGIN = 64;
    int treeNodeTopMargin = 64; //
    int treeNodeLeftMargin = 64; //

    final static int TREE_NODE_TEXT_SIZE = 20;
    private float treeNodeTextSize = 20; // 文字大小

    final static int LINE_WIDTH = 2;
    int lineWidth = 2;// 线条粗度
    private TextView currentTextView;


    /**
     * 缩放
     *
     * @param flag 小于0为缩小，大于0为放大，0为重置到100%
     */
    public void reScale(int flag) {
        // 最多放大9次，缩小9次
        // 为原来的0.07508468627929688/7.450580596923828
        int unit = 25; // 默认放大
        if (flag == 0) { // 重置到原来
            percent = 100;
        } else if (flag < 0) { // 缩小
            unit = -unit;
        }
        percent = percent + percent * unit / 100;

        calcPercent(percent);
        initWithTree();
        //measure(0, 0); // 如果不调用这个函数会导致空白截断
        Toast.makeText(getContext(), String.format("已经缩放到%d%%", percent), Toast.LENGTH_SHORT).show();
    }

    static class ScaleSate {
        public final static int NORMAL = 0;
        public final static int FULL = 1;
        public final static int FULL_WIDTH = 2;
        public final static int FULL_HEIGHT = 3;


        public final static int SIZE = 2; // todo 暂只使用两种情况
    }


    public TRLayout(Context context) {
        super(context);
    }

    public TRLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TRLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        setClipChildren(false);
        setClipToPadding(false);


        mPaint = new Paint();
        mPaint.setAntiAlias(true);

        mPath = new Path();
        mPath.reset();

        mContext = context;

        conf = TRConfig.getInstance();

//        setMinWidth(0);
//        setMinHeight(0);

        setMinimumWidth(0);//必须同时设置这个
        setMinimumHeight(0);//必须同时设置这个

        setOnClickListener(v -> {
            // 将选中的清除掉
            if (currentTextView != null) {
                currentTextView.setBackgroundColor(Color.parseColor("#00000000"));
            }
        });

        initScale();
    }

    public TRItemTree getItemTree() {
        return mItemTree;
    }

    public void setItemTree(TRItemTree mItemTree) {
        this.mItemTree = mItemTree;

        if (mItemTree == null) {
            LOG.jLoge("未初始化树！！！mItemTree=null");
            return;
        }
    }


    public void initWithTree() {
        removeAllViews();

//        mInvalidateLayout = false;
        int w = QMUIDisplayHelper.dp2px(getContext(), treeNodeWidth);
        int h = QMUIDisplayHelper.dp2px(getContext(), treeNodeHeight);
        int lm = QMUIDisplayHelper.dp2px(getContext(), treeNodeLeftMargin);
        int tm = QMUIDisplayHelper.dp2px(getContext(), treeNodeTopMargin);
        mItemTree.setNodeWidth(w);
        mItemTree.setNodeHeight(h);
        mItemTree.setNodeLeftMargin(lm);
        mItemTree.setNodeTopMargin(tm);


        if (mItemTree == null) {
            LOG.jLoge("未初始化树！！！mItemTree=null");
            return;
        }

        // 计算行列
        mItemTree.calcColumnAndRow();


//        setMinimumHeight(mItemTree.getMaxBottom());
//        setMinimumWidth(mItemTree.getMaxRight());
//        setMeasureAllChildren(true);

        // todo row count and column count not right
        // 从实际的节点从1开始，另加一个作为冗余，所以+2
        // 列增加了一列作为画线的展示
//        int c = mItemTree.getColumnCount() * 2 + 1;
//        int r = mItemTree.getRowCount() + 3;
//        if (conf.isShowVertical()) {
//            int t = c;
//            c = r;
//            r = t;
//        }


        mTextViewMap = new HashMap<>();

//        LOG.jLogi("gridlayout row=%d,column=%d", this.getRowCount(), this.getColumnCount());

        if (conf.isShowColumnTips()) {
            // 添加第一行的提示
//            for (int i = 0; i < this.getColumnCount() - 1; i++) {
//                String text = String.format("第%d列", i + 1);
//                //LOG.jLogi(text);
//                addViewTips(LinearLayout.HORIZONTAL, 0, i + 1);
//
//            }
        }

        if (conf.isShowRowTips()) {
//            // 添加第一列的提示
//            for (int i = 0; i < this.getRowCount() - 1; i++) {
//                String text = String.format("第%d行", i + 1);
//                //LOG.jLogi(text);
//                addViewTips(LinearLayout.VERTICAL, i + 1, 0);
//            }
        }

        // 显示每一个节点
        Iterator iter = mItemTree.entrySet().iterator();
        while (iter.hasNext()) {
            HashMap.Entry entry = (HashMap.Entry) iter.next();
            TRItemNode item = (TRItemNode) entry.getValue();
//            String text = item.toString();
            int imgId = conf.getImgId(item.getSex());
//
//            int row = item.getRow() + 1;
//            int column = item.getColumn() * 2 + 1;


            // 如果是垂直的话，需要转置
//            if (conf.isShowVertical()) {
//                int t = row;
//                row = column;
//                column = t;
//            }

            Drawable imgDrawable = null;
            String imgPath = item.getImage();

            if (conf.isUseCustomedImg() && null != imgPath && !imgPath.equals("")) {
                imgDrawable = Drawable.createFromPath(imgPath);
            }
            if (imgDrawable == null) { // 如果上一部没有创建成功，也会调用这里
                imgDrawable = getResources().getDrawable(imgId);
            }

            TextView textView = addTextView(imgDrawable, item.getCallname(), item.getName());

            this.mTextViewMap.put(item.getId(), textView);
            textView.setTag(item.getId());
            textView.setOnLongClickListener(v -> {
                mLongClickListener.onLongClick(v);
                return true;
            });
            textView.setOnClickListener(v -> {
                v.setBackgroundColor(getResources().getColor(R.color.select_textview));
                // 如果选中了一个，且不是当前的
                if (currentTextView != null && v != currentTextView) {
                    currentTextView.setBackgroundColor(Color.parseColor("#00000000"));
                }
                // 如果选中的是当前的，就不选中
                if (currentTextView == v) {
                    currentTextView.setBackgroundColor(Color.parseColor("#00000000"));
                    currentTextView = null;
                    return;
                }
                currentTextView = (TextView) v;

            });
            textView.setEllipsize(TextUtils.TruncateAt.MIDDLE);
            textView.setMaxLines(2);
            textView.setMaxWidth(QMUIDisplayHelper.dp2px(getContext(), treeNodeWidth));

        }
        measure(0, 0);

    }

    public void setSelected(int id) {
        TextView v = mTextViewMap.get(id);
        setSelected(v);
    }

    public void setSelected(TextView v) {
        if (v == null) {
            return;
        }
        // 高亮，且不能再点击
        v.setBackgroundColor(getResources().getColor(R.color.select_textview_hilight));
        v.setOnClickListener(v1 -> {
        });
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measureChildren(widthMeasureSpec, heightMeasureSpec);
        if (mTextViewMap == null) {
            return;
        }

        Iterator iter = mItemTree.entrySet().iterator();
        while (iter.hasNext()) {
            HashMap.Entry entry = (HashMap.Entry) iter.next();
            TRItemNode item = (TRItemNode) entry.getValue();

            int id = item.getId();
            TextView textView = mTextViewMap.get(id);

            int width = textView.getMeasuredWidth();
            int height = textView.getMeasuredHeight();


            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(width, height);
            params.gravity = Gravity.LEFT;
            if (conf.isShowVertical()) { // 垂直的话，直接转置
                params.topMargin = item.getLeft() + width / 2;
                params.leftMargin = item.getTop() + height / 2;
                if (item.getTop() == 0) {
                    params.leftMargin = 0;
                }
                if (item.getLeft() == 0) {
                    params.topMargin = 0;
                }
            } else {
                params.leftMargin = item.getLeft() + width / 2;
                params.topMargin = item.getTop() + height / 2;
                if (item.getTop() == 0) {
                    params.topMargin = 0;
                }
                if (item.getLeft() == 0) {
                    params.leftMargin = 0;
                }
            }
            textView.setLayoutParams(params);

        }


    }

    private TextView addTextView(Drawable imgDrawable, String callname, String name) {

        TextView textView = new TextView(mContext);
//        String text = callname + "\n" + name;

        if (callname != null) {
            textView.append(callname);
        }
        if (callname != null && name != null) {
            textView.append("\n");
        }
        if (name != null) {
            SpannableString spanText = new SpannableString(name);
            spanText.setSpan(new ForegroundColorSpan(Color.GRAY), 0, name.length(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

            textView.append(spanText);
        }


        textView.setGravity(Gravity.CENTER);
//        textView.setBackgroundResource(0);
//        int padding = dp2px(getContext(), 5);
//        textView.setPadding(padding, padding, padding, padding);
        textView.setTextSize(treeNodeTextSize);


        int width = dp2px(getContext(), treeNodeWidth);
        int height = dp2px(getContext(), treeNodeWidth);

        if (conf.isShowImg() && imgDrawable != null) {

            imgDrawable.setBounds(0, 0, width, height);
            textView.setCompoundDrawables(null, imgDrawable, null, null);
        }

        addView(textView);

        return textView;

    }


    @Override
    protected void dispatchDraw(Canvas canvas) {


        if (mItemTree != null && !mItemTree.isEmpty() && mTextViewMap != null && !mTextViewMap.isEmpty()) {

            Iterator iter = mItemTree.entrySet().iterator();
            while (iter.hasNext()) {
                HashMap.Entry entry = (HashMap.Entry) iter.next();
                TRItemNode item = (TRItemNode) entry.getValue();

                int id = item.getId();
                int mid = item.getMid();
                int fid = item.getFid();
//                if (item.getColor ()== mColorDrawLine) { // todo 着色是否需要?
//                    continue;
//                }


                item.setColor((item.getColor() + 1) % 2);

                View self = this.mTextViewMap.get(id);
                View father = this.mTextViewMap.get(fid);
                View mother = this.mTextViewMap.get(mid);

                // 计算出画线的偏移，行相差较远的就偏移
                int lineGap = 0;
                int color = R.color.tree_grid_line;
                TRItemNode fItem = getItemTree().getFather(item);
                TRItemNode mItem = getItemTree().getMother(item);
                if (fItem != null && mItem != null) {
                    int x = Math.abs(fItem.getRow() - mItem.getRow());
                    if (x > 1) {
                        lineGap = (x % 3+1) * dp2px(mContext, lineWidth) * 3;
                        color = R.color.tree_grid_line_other;
                    }
                }


                if (self != null) {
                    if (getItemTree().hasFather(item)) {
                        drawLineToView(canvas, father, self, lineGap, color);
                    }
                    if (getItemTree().hasMother(item)) {
                        drawLineToView(canvas, mother, self, lineGap, color);
                    }
                }
            }

        }

        super.dispatchDraw(canvas);

    }


    /**
     * 绘制两个View直接的连线
     *
     * @param canvas
     * @param from
     * @param to
     * @param lineGap
     */
    private void drawLineToView(Canvas canvas, View from, View to, int lineGap, int color) {

        if (to.getVisibility() == GONE) {
            return;
        }
        if (from == null || to == null || canvas == null) {
            return;
        }

        mPaint.setStyle(Paint.Style.STROKE);


        mPaint.setStrokeWidth(dp2px(mContext, lineWidth));
        mPaint.setColor(mContext.getResources().getColor(color));

        int top = from.getTop();
        int fromY = top + from.getMeasuredHeight() / 2;
        int fromX = from.getRight();


        int top1 = to.getTop();
        int toY = top1 + to.getMeasuredHeight() / 2;
        int toX = to.getLeft();

        int gap = (toX - fromX) / 5;

        int pointX1 = fromX + gap + lineGap;
        int pointY1 = fromY;

        int pointX2 = pointX1;
        int pointY2 = toY;

        if (conf.isShowVertical()) {
            fromY = from.getBottom();
            fromX = from.getLeft() + from.getMeasuredWidth() / 2;

            toY = to.getTop();
            toX = to.getLeft() + to.getMeasuredWidth() / 2;


            gap = (toY - fromY) / 5;

            pointX1 = fromX;
            pointY1 = fromY + gap + lineGap;

            pointX2 = toX;
            pointY2 = pointY1;

        }


        mPath.reset();
        mPath.moveTo(fromX, fromY);
        mPath.lineTo(pointX1, pointY1);
        mPath.moveTo(pointX1, pointY1);
        mPath.lineTo(pointX2, pointY2);
        mPath.moveTo(pointX2, pointY2);
        mPath.lineTo(toX, toY);

        canvas.drawPath(mPath, mPaint);
    }

    public void setItemLongClickListener(OnLongClickListener mLongClickListener) {
        this.mLongClickListener = mLongClickListener;
    }

    public HashMap<Integer, TextView> getTextViewMap() {
        return mTextViewMap;
    }


    // ---------------------------------------------------------------
    // star of 缩放功能

    // 双击缩放到100%, 全部显示
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 返回给ScaleGestureDetector来处理
//        LOG.jLoge("TreeGridLayout touched!");

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            long newClickTime = System.currentTimeMillis();
            Log.i("ABC", "newClickTime=" + System.currentTimeMillis());
            Log.i("ABC", "cha=" + (newClickTime - mClickTime));
            if (newClickTime - mClickTime < 250) {//调用双击事件
                flipScaleTreeGridLayout();
            } else {
                mClickTime = newClickTime;
            }
        }
        super.onTouchEvent(event);
        return scaleGestureDetector.onTouchEvent(event);
    }


    public void resizeTree(int pPercent) {
        calcPercent(pPercent);
        initWithTree();
        //measure(0, 0);
    }

    private void calcPercent(int pPercent) {
        // 最多只能缩小到5%
        if (pPercent < 7) {
            pPercent = 7;
        } else if (pPercent > 745) {
            pPercent = 745;
        }
        // 这里把大小记住了
        percent = pPercent;

        treeNodeTipsGapHorizontal = TREE_NODE_TIPS_GAP_HORIZONTAL * pPercent / 100;
        treeNodeTipsGapVertical = TREE_NODE_TIPS_GAP_VERTICAL * pPercent / 100;
        treeNodeTextSize = TREE_NODE_TEXT_SIZE * pPercent / 100;

        treeNodeTopMargin = TREE_NODE_TOP_MARGIN * pPercent / 100; //
        treeNodeLeftMargin = TREE_NODE_LEFT_MARGIN * pPercent / 100; //
        treeNodeWidth = TREE_NODE_WIDTH * pPercent / 100;
        treeNodeHeight = TREE_NODE_HEIGHT * pPercent / 100;

        lineWidth = (int) (LINE_WIDTH * pPercent / 100);


        LOG.jLoge("percent = %d, mColumnSize=%d", percent, mItemTree.getColumnCount());
    }

    /**
     * 缩放到合适的大小，以观全览
     */
    public void flipScaleTreeGridLayout() {
        scaleState = (scaleState + 1) % ScaleSate.SIZE;
        percent = calcFullPercent(scaleState);
        LOG.jLogd("percent=%d", percent);
        resizeTree(percent);
    }

    int calcFullPercent(int state) {
        // NOTE: 由于四舍五入的问题，并不能完全全屏，会有一些小的误差
        float scale = 1.0f;

        // ALERT: 这里的view，如果还没渲染，得到的height,width会为0!!!
        View view = (View) this.getParent();
        LOG.jLoge("this.getMeasuredHeight=%d, view.getMeasuredHeight=%d",
                this.getMeasuredHeight(), view.getMeasuredHeight());
        LOG.jLoge("this.getMeasuredHeight=%d, view.getMeasuredHeight=%d",
                this.getMeasuredWidth(), view.getMeasuredWidth());
        float y = view.getMeasuredHeight() * 1.0f / this.getMeasuredHeight();
        float x = view.getMeasuredWidth() * 1.0f / this.getMeasuredWidth();

        switch (state) {
            case ScaleSate.NORMAL:
                scale = 1.0f;
                break;
            case ScaleSate.FULL:
                if (y > x) { // 使用小的那个，确保全部都能看到
                    scale = x;
                } else {
                    scale = y;
                }
                break;
            case ScaleSate.FULL_HEIGHT:
                scale = y;
                break;
            case ScaleSate.FULL_WIDTH:
                scale = x;
                break;
            default:
                break;
        }

        percent = (int) (100.0 * scale);

//        LOG.jLoge("percent = %d, scale=%f, mColumnSize=%d", percent, scale, mItemTree.getColumnCount());
        return percent;
    }

    public void setFullPercent() {

//        scaleState = ScaleSate.FULL_WIDTH;
//        percent = calcFullPercent(scaleState);
//        LOG.jLogd("percent=%d", percent);
//        resizeTree(percent);
//
        int[][] fullScreeList = new int[][]{
                {0, 100},
                {1, 100},
                {2, 82},
                {3, 53},
                {4, 45},
                {5, 38},
                {6, 31},
                {7, 25},
                {8, 23},
                {9, 21},
                {10, 18},
                {11, 14},
                {12, 11},
                {13, 9},
                {14, 8},
                {15, 8},
                {16, 7},
                {17, 7},
                {18, 7}
        };
        percent = 7;

        mItemTree.calcColumn();
        if (mItemTree.getErr() != null) {
            Toast.makeText(getContext(), mItemTree.getErr(), Toast.LENGTH_SHORT).show();
        }
        int count = mItemTree.getColumnCount();
        if (count < fullScreeList.length) {
            percent = fullScreeList[count][1];
        }

        calcPercent(percent);
    }

    // ---------------------------------------------------------------
    // start of 缩放功能


    /**
     * 控件宽度
     */
    private int mWidth;
    /**
     * 控件高度
     */
    private int mHeight;
    /**
     * 拿到src的图片
     */
//    private Drawable mDrawable;
    /**
     * 图片宽度（使用前判断mDrawable是否null）
     */
    private int mDrawableWidth;
    /**
     * 图片高度（使用前判断mDrawable是否null）
     */
    private int mDrawableHeight;

    /**
     * 初始化缩放值
     */
    private float mScale;

    /**
     * 双击图片的缩放值
     */
    private float mDoubleClickScale;

    /**
     * 最大的缩放值
     */
    private float mMaxScale;

    /**
     * 最小的缩放值
     */
    private float mMinScale;

    private ScaleGestureDetector scaleGestureDetector;
    /**
     * 当前有着缩放值、平移值的矩阵。
     */
    private Matrix matrix;

    public void initScale() {
//        setOnTouchListener(this);
        scaleGestureDetector = new ScaleGestureDetector(getContext(), this);
        initListener();
    }

//    public void setDrawable(Drawable drawable) {
//        this.mDrawable = drawable;
//    }

    /**
     * 初始化事件监听
     */
    private void initListener() {
        // 强制设置模式
//        setScaleType(ImageView.ScaleType.MATRIX);
        // 添加观察者
        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // 移除观察者
                getViewTreeObserver().removeGlobalOnLayoutListener(this);


//
//                // 获取控件大小
//                mWidth = getWidth();
//                mHeight = getHeight();
//
//                //通过getDrawable获得Src的图片
//                mDrawable = getDrawable();
//                if (mDrawable == null)
//                    return;
//                mDrawableWidth = mDrawable.getIntrinsicWidth();
//                mDrawableHeight = mDrawable.getIntrinsicHeight();
//                initImageViewSize();
//                moveToCenter();
            }
        });
    }

//    /**
//     * 初始化资源图片宽高
//     */
//    private void initImageViewSize() {
//        if (mDrawable == null)
//            return;
//
//        // 缩放值
//        float scale = 1.0f;
//        // 图片宽度大于控件宽度，图片高度小于控件高度
//        if (mDrawableWidth > mWidth && mDrawableHeight < mHeight)
//            scale = mWidth * 1.0f / mDrawableWidth;
//            // 图片高度度大于控件宽高，图片宽度小于控件宽度
//        else if (mDrawableHeight > mHeight && mDrawableWidth < mWidth)
//            scale = mHeight * 1.0f / mDrawableHeight;
//            // 图片宽度大于控件宽度，图片高度大于控件高度
//        else if (mDrawableHeight > mHeight && mDrawableWidth > mWidth)
//            scale = Math.min(mHeight * 1.0f / mDrawableHeight, mWidth * 1.0f / mDrawableWidth);
//            // 图片宽度小于控件宽度，图片高度小于控件高度
//        else if (mDrawableHeight < mHeight && mDrawableWidth < mWidth)
//            scale = Math.min(mHeight * 1.0f / mDrawableHeight, mWidth * 1.0f / mDrawableWidth);
//        mScale = scale;
//        mMaxScale = mScale * 8.0f;
//        mMinScale = mScale * 0.5f;
//    }

//    /**
//     * 移动控件中间位置
//     */
//    private void moveToCenter() {
//        final float dx = mWidth / 2 - mDrawableWidth / 2;
//        final float dy = mHeight / 2 - mDrawableHeight / 2;
//        matrix = new Matrix();
//        // 平移至中心
//        matrix.postTranslate(dx, dy);
//        // 以控件中心作为缩放
//        matrix.postScale(mScale, mScale, mWidth / 2, mHeight / 2);
//        setImageMatrix(matrix);
//    }

//    /**
//     * @return 当前缩放的值
//     */
//    private float getmScale() {
//        float[] floats = new float[9];
//        matrix.getValues(floats);
//        return floats[Matrix.MSCALE_X];
//    }

//    /**
//     * @param matrix 矩阵
//     * @return matrix的 l t b r 和width，height
//     */
//    private RectF getRectf(Matrix matrix) {
//        RectF f = new RectF();
//        if (mDrawable == null)
//            return null;
//        f.set(0, 0, mDrawableWidth, mDrawableHeight);
//        matrix.mapRect(f);
//        return f;
//    }

    @Override
    public boolean onScale(ScaleGestureDetector detector) {


        // 系统定义的缩放值
        float scaleFactor = detector.getScaleFactor();
        // 获取已经缩放的值
        float scale = percent;
        float scaleResult = scale * (0.90f*scaleFactor);

        if (scaleResult >= 500 && scaleFactor > 1.0f)
            scaleResult = 500;
        if (scaleResult <= 7 && scaleFactor < 1.0f)
            scaleResult = 7;


        calcPercent((int) scaleResult);
        initWithTree();
        LOG.jLoge("onScale: pecent = %d", percent);

        return false;
    }


    @Override
    public boolean onScaleBegin(ScaleGestureDetector detector) {
        return true;
    }

    @Override
    public void onScaleEnd(ScaleGestureDetector detector) {
        calcPercent(percent);
        initWithTree();
        invalidate();
//        mItemTree.getPercent
//        float scale = getmScale();
//        if (scale < mScale) {
//            matrix.postScale(mScale / scale, mScale / scale, mWidth / 2, mHeight / 2);
//            setImageMatrix(matrix);
//        }
    }


    private float downX;
    private float downY;
    private float nowMovingX;
    private float nowMovingY;
    private float lastMovedX;
    private float lastMovedY;
    private boolean isFirstMoved = false;

//    @Override
//    public boolean onTouch(View v, MotionEvent event) {
////        switch (event.getAction() & MotionEvent.ACTION_MASK) {
////            case MotionEvent.ACTION_DOWN:
////                isFirstMoved = false;
////                downX = event.getX();
////                downY = event.getY();
////                break;
////            case MotionEvent.ACTION_POINTER_DOWN:
////                isFirstMoved = false;
////                break;
////            case MotionEvent.ACTION_MOVE:
////                nowMovingX = event.getX();
////                nowMovingY = event.getY();
////                if (!isFirstMoved) {
////                    isFirstMoved = true;
////                    lastMovedX = nowMovingX;
////                    lastMovedY = nowMovingY;
////                }
////                float dX = 0.0f;
////                float dY = 0.0f;
////                RectF rectf = getRectf(matrix);
////                // 判断滑动方向
////                final float scrollX = nowMovingX - lastMovedX;
////                // 判断滑动方向
////                final float scrollY = nowMovingY - lastMovedY;
////                // 图片高度大于控件高度
////                if (rectf.height() > mHeight && canSmoothY()) {
////                    dY = nowMovingY - lastMovedY;
////                }
////
////                // 图片宽度大于控件宽度
////                if (rectf.width() > mWidth && canSmoothX()) {
////                    dX = nowMovingX - lastMovedX;
////                }
////                matrix.postTranslate(dX, dY);
////
////                remedyXAndY(dX, dY);
////
////                lastMovedX = nowMovingX;
////                lastMovedY = nowMovingY;
////                break;
////            case MotionEvent.ACTION_UP:
////                break;
////            case MotionEvent.ACTION_POINTER_UP:
////                isFirstMoved = false;
////                break;
////        }
//        return scaleGestureDetector.onTouchEvent(event);
//    }

//    /**
//     * 判断x方向上能不能滑动
//     *
//     * @return 可以滑动返回true
//     */
//    private boolean canSmoothX() {
//        RectF rectf = getRectf(matrix);
//        if (rectf.left > 0 || rectf.right < getWidth())
//            return false;
//        return true;
//    }

//    /**
//     * 判断y方向上可不可以滑动
//     *
//     * @return 可以滑动返回true
//     */
//    private boolean canSmoothY() {
//        RectF rectf = getRectf(matrix);
//        if (rectf.top > 0 || rectf.bottom < getHeight())
//            return false;
//        return true;
//    }

//    /**
//     * 纠正出界的横和众线
//     *
//     * @param dx 出界偏移的横线
//     * @param dy 出街便宜的众线
//     */
//    private void remedyXAndY(float dx, float dy) {
//        if (!canSmoothX())
//            matrix.postTranslate(-dx, 0);
//        if (!canSmoothY())
//            matrix.postTranslate(0, -dy);
//        setImageMatrix(matrix);
//    }


    // end of 缩放功能
    // ---------------------------------------------------------------
}
